import os
from CalTorque import GetSheetData,OpenCalTorqueXLS,AddCalTube
from datetime import datetime
from PlotCalTorque import PlotCalTorque 
from string import Template
import cPickle
import numpy
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as PLT
from matplotlib import dates
import matplotlib

data_files = []
dp = 'data/'
ls= os.listdir(dp)
for i in ls:
   if 'in' not in i: continue
   data_files.append(dp+i)
dp = 'data2/'
ls= os.listdir(dp)
for i in ls:
   if 'in' not in i: continue
   data_files.append(dp+i)

all_in = [] #numpy.array()
all_out = [] #numpy.array()

bins = 400
max_d = 400
x_inputs = numpy.zeros(bins)
X = numpy.linspace(0,max_d,bins)
Y = numpy.zeros(bins)

for f in data_files:
   if (f.split('.')[-1] not in ['xlsx', 'xls']):
      continue
   print f
   book = OpenCalTorqueXLS(f)
   data = GetSheetData(book)
   data['direction'] = f.split(' ')[2].split('_')[1].split('.')[0]
   if data['direction'] != 'in':
      continue #Skip all non-insertions
   for j,x in enumerate(X):
      pos_torque = []
      x0 = x-(max_d/bins)/2.
      x1 = x+(max_d/bins)/2.
      for i,p in enumerate(data['position']):
         if p>x0 and p<=x1:
            pos_torque.append(data['torque_inoz'][i])
      if len(pos_torque)>0:
         Y[j] += max(pos_torque)
         x_inputs[j]+=1.
for i,n in enumerate(x_inputs):
   if n==0: continue
   Y[i] = Y[i]/n
   
fig = PLT.figure(figsize=(15,8),dpi=150)
box = [0.14, 0.14, 0.76, 0.76]
ax1 = fig.add_axes(box)
ax1.set_xlabel('Position (cm)')
ax1.set_ylabel('Torque (in.oz)')
PLT.title('Average of all IN deployments')
ax1.grid()
PLT.plot(X,Y)
fig.savefig('average_in.png')
